﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using BCCommon.Enums;
using BCDto.WxLogin;
using BCDto.WxLogin.WebLogin;
using BCService.Sim.Admin.AdminAuth;
using BCService.WeChatComponent.WeChatLoginService;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace BCTMSRESTful.Controllers.Anonymous
{
    [Route("api/v1/[controller]")]
    [ApiController]
    public class WxLoginController : BCTMSRESTfulAPIController
    {
        private readonly IAdminAuthService adminAuthService;
        private readonly IWeChatLoginService weChatLoginService;
        public WxLoginController(IAdminAuthService adminAuthService, IWeChatLoginService weChatLoginService)
        {
            this.adminAuthService = adminAuthService;
            this.weChatLoginService = weChatLoginService;
        }
        #region 废弃微信二维码登录
        
        #region 获取微信扫码登录二维码
        /// <summary>
        ///  获取微信扫码登录二维码
        /// </summary>
        /// <response code="201">添加销售购物车成功</response>
        /// <response code="400">请求参数或输入的数据不正确。</response>
        /// <response code="500">服务器发生错误。</response>
        /// <response code="501">某些功能尚未实现。</response>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(WxLoginDto), 201)]
        public IActionResult Post()
        {
            string appid = "wxaefbbc303e960337";
            string redirectUri = "https%3A%2F%2Fsim.xablackcoffee.com%2F%23%2Fapp%2Flogincheck";
            string responseType = "code";
            string state = "";
            string url = string.Format("https://open.weixin.qq.com/connect/qrconnect?appid={0}&scope=snsapi_login&redirect_uri={1}&state={2}&response_type={3}", appid, redirectUri, state, responseType);
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentLength = 0;
            request.ContentType = "json";
            request.Timeout = 10000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            bool bResult = (response.StatusCode == HttpStatusCode.OK);
            if (!bResult)
            {
                throw new ArgumentException("获取微信登录信息失败");
            }
            string jsonString = string.Empty;

            #region 读取response响应并更新数据库
            using (var responseStream = response.GetResponseStream())
            {
                if (responseStream != null)
                {
                    using (var reader = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        jsonString = reader.ReadToEnd();
                    }
                }
            }
            #endregion
            Regex regex = new Regex("[\\\"](https://)(.*)[^\\\"]");
            string source = jsonString;
            string qrurl = string.Empty;
            string uuid = string.Empty;
            while (regex.IsMatch(jsonString))
            {
                string value = regex.Match(jsonString).Value;
                if (value.Contains("uuid="))
                {
                    uuid = value.Substring(value.IndexOf("uuid=")).Replace("uuid=","").Replace("\"", "").Replace("\n", "");
                    qrurl = value.Replace("\"", "").Replace("\n", "");
                    jsonString = qrurl;
                }
                else
                {
                    jsonString = jsonString.Replace(value, "");
                }
            }


            return StatusCode((int)HttpStatusCode.Created, new { uuid=uuid, qrurl = qrurl, source = source });

            //https://lp.open.weixin.qq.com/connect/l/qrconnect?uuid=041QOrRx2BYf000q&_=1600956397374
            // [\"](https://)(.*)[^\"]
        }
        #endregion

        #region 保持微信扫码连接
        /// <summary>
        ///  保持微信扫码连接
        /// </summary>
        /// <param name="uuid">uuid</param>
        /// <param name="last">最后时间</param>
        /// <response code="201">添加销售购物车成功</response>
        /// <response code="400">请求参数或输入的数据不正确。</response>
        /// <response code="500">服务器发生错误。</response>
        /// <response code="501">某些功能尚未实现。</response>
        /// <returns></returns>
        [HttpGet("[action]")]
        [ProducesResponseType(typeof(string), 200)]
        public IActionResult QRConnect([FromQuery(Name = "uuid")]string uuid, [FromQuery(Name = "last")]long last)
        {
            string url = string.Format("https://long.open.weixin.qq.com/connect/l/qrconnect?uuid={0}&_={1}", uuid,last);
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentLength = 0;
            request.ContentType = "script";
            request.Timeout = 10000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            bool bResult = (response.StatusCode == HttpStatusCode.OK);
            if (!bResult)
            {
                throw new ArgumentException("发送微信扫码心跳失败");
            }
            string jsonString = string.Empty;

            #region 读取response响应并更新数据库
            using (var responseStream = response.GetResponseStream())
            {
                if (responseStream != null)
                {
                    using (var reader = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        jsonString = reader.ReadToEnd();
                    }
                }
            }
            #endregion
            string result = jsonString.Substring(jsonString.LastIndexOf("wx_code=")).Replace("wx_code=","").TrimEnd(';').TrimStart('\'').TrimEnd('\'');
            return StatusCode((int)HttpStatusCode.OK,new { Data= result, State=true });
        }
        #endregion

        #endregion

        #region 获取微信AccessToken(服务端)
        /// <summary>
        ///  获取微信AccessToken(服务端)
        /// </summary>
        /// <param name="code">code码</param>
        /// <response code="200">获取微信AccessToken成功</response>
        /// <response code="400">请求参数或输入的数据不正确。</response>
        /// <response code="500">服务器发生错误。</response>
        /// <response code="501">某些功能尚未实现。</response>
        /// <returns></returns>
        [HttpGet("[action]")]
        [ProducesResponseType(typeof(WxLoginWebAccessTokenDto), 200)]
        public IActionResult SimToken([FromQuery(Name = "code")]string code)
        {
            WxLoginWebAccessTokenDto accessTokenDto = this.weChatLoginService.GetAccessToken(code, true);
            
            var adminAuthDto = this.adminAuthService.Get(AuthType.WeChat, accessTokenDto.unionid);
            accessTokenDto.exists = adminAuthDto != null;

            return StatusCode((int)HttpStatusCode.OK, accessTokenDto);

        }
        #endregion

        #region 获取微信AccessToken（用户端）
        /// <summary>
        ///  获取微信AccessToken（用户端）
        /// </summary>
        /// <param name="code">code码</param>
        /// <response code="200">获取微信AccessToken成功</response>
        /// <response code="400">请求参数或输入的数据不正确。</response>
        /// <response code="500">服务器发生错误。</response>
        /// <response code="501">某些功能尚未实现。</response>
        /// <returns></returns>
        [HttpGet("[action]")]
        [ProducesResponseType(typeof(WxLoginWebAccessTokenDto), 200)]
        public IActionResult Token([FromQuery(Name = "code")]string code)
        {
            WxLoginWebAccessTokenDto accessTokenDto = this.weChatLoginService.GetAccessToken(code, false);
            
            
            return StatusCode((int)HttpStatusCode.OK, accessTokenDto);
        }
        #endregion
    }
}
